package com.yang.Runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yang.constants.SystemConstants;

import com.yang.domain.entity.Article;
import com.yang.mapper.ArticleMapper;
import com.yang.utils.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yang.constants.RedisConstants.ARTICLE_VIEWCOUNT;

/**
 * 在应用启动时把博客的浏览量存储到redis中
 * @author Admin
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisCache redisCache;


    @Override
    public void run(String... args) {
        //1.查询出所有状态正常的文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleMapper.selectList(queryWrapper);

        //2.将list集合转换map，文章id和游览量
        Map<String, Integer> viewCountMap = articleList.stream().collect(
                Collectors.toMap(article -> article.getId().toString(), article -> article.getViewCount().intValue())
        );

        //3.写入到redis中
       redisCache.setCacheMap(ARTICLE_VIEWCOUNT,viewCountMap);

    }
}
